package com.example.lin.togglebutton.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class TouchEventStudyView extends View {

    String TAG = "TAG";
    private Paint paint;

    public TouchEventStudyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    private void initPaint() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
    }


    private float lastX;
    private float lastY;


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(x, y, 50, paint);
    }


    private float x;
    private float y;

    /**
     * 触摸
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = event.getX();
        y = event.getY();
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                Log.d("TAG", "onTouchEvent: 按下" + x + "," + y);
                break;
            case MotionEvent.ACTION_MOVE:
//                Log.d("TAG", "onTouchEvent: 滑动" + x + "," + y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                Log.d("TAG", "onTouchEvent: 抬起" + x + "," + y);
                float xDistance = Math.abs(lastX - x);
                float yDistance = Math.abs(lastY - y);
                if (xDistance > 20 || yDistance > 20) {
                    if (xDistance > yDistance) {
                        //左右方向
                        if (lastX < x) {
                            Log.d(TAG, "onTouchEvent: 向右");
                        } else {
                            Log.d(TAG, "onTouchEvent: 向左");
                        }
                    } else {
                        //上下方向
                        if (lastY < y) {
                            Log.d(TAG, "onTouchEvent: 向下");
                        } else {
                            Log.d(TAG, "onTouchEvent: 向上");
                        }
                    }
                }
                break;
        }
        return true;
    }
}
